package com.hmall.trade.listener;

import com.hmall.api.client.PayClient;
import com.hmall.api.dto.PayOrderDTO;
import com.hmall.trade.constants.MQConstants;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@RequiredArgsConstructor
public class OrderStatusListener {
    private final IOrderService orderService;
    private final PayClient payClient;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MQConstants.ORDER_QUEUE, durable = "true"),
            exchange = @Exchange(value = MQConstants.ORDER_EXCHANGE, delayed = "true"),
            key = MQConstants.ORDER_ROUTING_KEY
    ))
    public void handleOrderStatus(Long orderId) {
        log.info("收到订单状态消息，订单id:{}", orderId);
        // 根据订单id查询订单
        Order order = orderService.getById(orderId);
        // 判断订单的支付状态，如果是已支付或者订单压根不存在，则直接return
        if (order == null || order.getStatus() != 1) {
            // 订单不存在，或者已经被处理（被支付）
            return;
        }
        // 否则 查询支付单的支付状态（使用远程调用pay-service，查pay_order表，条件是：biz_order_no等于orderId）
        PayOrderDTO payOrderDTO = payClient.queryPayOrderByBizOrderNo(orderId);
        // 如果是已支付，则修改订单状态为已支付
        if (payOrderDTO != null && payOrderDTO.getStatus() == 3) {
            orderService.markOrderPaySuccess(orderId);
        } else {
            // 否则,1.将订单中的商品库存恢复，2.取消订单，订单状态改成5(5、交易取消，订单关闭)
            orderService.cancelOrderById(orderId);

        }
    }
}
